package com.indictor.controller;


import com.indicator.base.constant.ControllerConstants;
import com.indictor.conf.RedisConfig;
import com.indictor.controller.parameter.IndicatorFormulaParameter;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.indicator.base.constant.ControllerConstants.*;


@RestController
@RequestMapping(INDICATOR_FORMULA)
public class IndicatorFormulaController {


    @PostMapping(ADD)
    public String add(@RequestBody List<IndicatorFormulaParameter> formulaParameters) {
        RedisCommands redisCommands = RedisConfig.getInstance().get();
        for (IndicatorFormulaParameter formulaParameter : formulaParameters) {
            redisCommands.zadd(FORMULA_REDIS+formulaParameter.getKey(), formulaParameter.getScore(), formulaParameter.getSubKey()+formulaParameter.getType());
        }
        return ControllerConstants.OK;
//        return ControllerConsßtants.OK;
    }


    @DeleteMapping(DELETE + DIAGONAL + KEY + DIAGONAL + "{subkey}")
    public String delete(@PathVariable String key, @PathVariable String subkey) {
        RedisCommands redisCommands = RedisConfig.getInstance().get();
        if (StringUtils.isEmpty(key)) {
            redisCommands.zrem(key);
        } else {
            redisCommands.zrem(key, subkey);
        }
        return ControllerConstants.OK;
    }

    @GetMapping(GET + DIAGONAL + KEY)
    public Map<String, Object> get(@PathVariable String key) {
        RedisCommands redisCommands = RedisConfig.getInstance().get();
        List<String> zrange = redisCommands.zrangeWithScores(key, 0, -1);
        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isEmpty(zrange))
            return map;

        int size = zrange.size() / 2;
        for (int i = 0; i < size; i+=2) {
            String s = zrange.get(i);
            String s1 = zrange.get(i + 1);
            map.put(s,s1);
        }
        return map;
    }


}
